package cn.lg.soar.database.handler;

import cn.lg.soar.common.util.current.ICurrentUser;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.database.base.entity.ITenantEntity;
import cn.lg.soar.database.config.DatabaseProperties;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class MyMetaObjectHandler implements MetaObjectHandler {

    private final boolean enabledTenant;

    public MyMetaObjectHandler(DatabaseProperties properties) {
        this.enabledTenant = properties.getEnabledTenant();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建时间
        LocalDateTime now = LocalDateTime.now();
        this.setFieldValByName("createTime", now, metaObject);
        this.setFieldValByName("updateTime", now, metaObject);
        // 创建人
        ICurrentUser user = UserContext.getUserOrDef();
        Long userId = user.getId(0L);
        this.setFieldValByName("createBy", userId, metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
        // 所属租户
        if (enabledTenant) {
            Integer tenantId = user.getCurrentTenantId(0);
            this.setFieldValByName(ITenantEntity.PROPERTY, tenantId, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        ICurrentUser user = UserContext.getUserOrDef();
        this.setFieldValByName("updateBy", user.getId(0L), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }

}
